package com.xiaoxing.salesclient.mvp.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;
import com.xiaoxing.salesclient.di.component.DaggerSheZhiComponent;
import com.xiaoxing.salesclient.di.module.SheZhiModule;
import com.xiaoxing.salesclient.mvp.contract.SheZhiContract;
import com.xiaoxing.salesclient.mvp.model.entity.UpdateUserInfo;
import com.xiaoxing.salesclient.mvp.model.entity.UploadMemberImage;
import com.xiaoxing.salesclient.mvp.presenter.SheZhiPresenter;
import com.xiaoxing.salesclient.mvp.ui.PaiMaiApplication;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonsdk.core.BaseConstants;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.Utils;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import xiaoxing.com.salesclient.R;
import xiaoxing.com.salesclient.R2;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.SALES_CLIENT_SHE_ZHI_ACTIVITY)
public class SheZhiActivity extends BaseActivity<SheZhiPresenter> implements SheZhiContract.View {


    public static int mCurrentDialogStyle = com.qmuiteam.qmui.R.style.QMUI_Dialog;

    @BindView(R2.id.img_tou_xiang)
    ImageView imgTouXiang;
    @BindView(R2.id.tv_name_value)
    TextView tvNameValue;
    @BindView(R2.id.tv_ni_cheng_value)
    TextView tvNiChengValue;
    @BindView(R2.id.tv_zhang_hao_value)
    TextView tvZhangHaoValue;
    @BindView(R2.id.tv_di_zhi_value)
    TextView tvDiZhiValue;
    @BindView(R2.id.tv_mi_ma_value)
    TextView tvMiMaValue;
    @BindView(R2.id.tv_email_value)
    TextView tvYouXiangValue;
    @BindView(R2.id.tv_tui_chu)
    TextView tv_tui_chu;
    @BindView(R2.id.tv_dian_hua_value)
    TextView tv_dian_hua_value;

    private BottomDialogUtil mBottomDialogUtilShare;


    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerSheZhiComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .sheZhiModule(new SheZhiModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_she_zhi; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, "個人中心");
        PhotoUtil.init(PaiMaiApplication.getContext(), new FrescoIniter());//第二个参数根据具体依赖库而定


        Glide.with(this).load(mSharedPreferencesHelper.getString(BaseConstants.COVER)).into(imgTouXiang);
        tvNiChengValue.setText(mSharedPreferencesHelper.getString(BaseConstants.NICKNAME));
        tvZhangHaoValue.setText(mSharedPreferencesHelper.getString(BaseConstants.USERNAME));
        tvMiMaValue.setText(mSharedPreferencesHelper.getString(BaseConstants.PASSWORD));
        tvDiZhiValue.setText(mSharedPreferencesHelper.getString(BaseConstants.ADDRESS));
        tvYouXiangValue.setText(mSharedPreferencesHelper.getString(BaseConstants.EMAIL));
        tv_dian_hua_value.setText(mSharedPreferencesHelper.getString(BaseConstants.PHONE));

        if (!TextUtils.isEmpty(mSharedPreferencesHelper.getString("gu_ke_uid"))) {
            tv_tui_chu.setVisibility(View.GONE);
            mSharedPreferencesHelper.removeString("gu_ke_uid");
        }

    }

    @Override
    public void showLoading() {
        LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtil.dismissDialog();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);

    }

    @Override
    public void killMyself() {
        finish();
    }

    public String[] getPermissions() {        //设置该界面所需的全部权限
        return new String[]{Manifest.permission.CAMERA};
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 103) {
            xiuGaiTouXiang();
        }
    }

    @OnClick({R2.id.ll_tou_xiang, R2.id.rl_xing_ming, R2.id.rl_ni_cheng, R2.id.rl_zhang_hao, R2.id.rl_xiu_gai_mi_ma, R2.id.rl_di_zhi, R2.id.tv_tui_chu, R2.id.rl_email, R2.id.rl_dian_hua})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.ll_tou_xiang) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                    ArmsUtils.makeText(SheZhiActivity.this, "請先開啟相機權限");
                    requestPermissions(getPermissions(), 103);
                    return;
                }
            }
            xiuGaiTouXiang();
        } else if (i == R.id.rl_xing_ming) {
//            showEditTextDialog("修改姓名", "請輸入姓名", tvNameValue);
        } else if (i == R.id.rl_ni_cheng) {
            showEditTextDialog("修改姓名", "請輸入姓名", tvNiChengValue, 1);
        } else if (i == R.id.rl_zhang_hao) {
        } else if (i == R.id.rl_xiu_gai_mi_ma) {
            showEditTextDialog("修改密碼", "請輸入密碼", tvMiMaValue, 3);
        } else if (i == R.id.rl_di_zhi) {
            showEditTextDialog("修改地址", "請輸入地址", tvDiZhiValue, 2);
        } else if (i == R.id.rl_email) {
            showEditTextDialog("修改郵箱", "請輸入郵箱", tvYouXiangValue, 4);
        } else if (i == R.id.rl_dian_hua) {
            showEditTextDialog("修改電話", "請輸入電話", tv_dian_hua_value, 5);
        } else if (i == R.id.tv_tui_chu) {
//            showConfirmMessageDialog();

            mPresenter.updateUserInfo(mSharedPreferencesHelper.getString(BaseConstants.TOKEN), tvNiChengValue.getText().toString(), tvDiZhiValue.getText().toString(), tvMiMaValue.getText().toString(), tvYouXiangValue.getText().toString(), tv_dian_hua_value.getText().toString().trim());

        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //onActivityResult里一行代码回调
        PhotoUtil.onActivityResult(this, requestCode, resultCode, data);

    }

    private void xiuGaiTouXiang() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)
                        /*.setFromCamera(false)
                        .setMaxSelectCount(5)
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(true)
                        .setCropRatio(16,9)*/
                        .start(SheZhiActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                imgTouXiang.setImageBitmap(getBitmap(compressedPath));
                                uploadMemberImage(compressedPath);
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);


                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = R.color.public_black;
                PhotoUtil.titleBarColor = R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(SheZhiActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                imgTouXiang.setImageBitmap(getBitmap(compressedPath));
                                uploadMemberImage(compressedPath);

                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(SheZhiActivity.this, root);

        mBottomDialogUtilShare.showDiaolog();


    }

    /**
     * 获取小尺寸的照片
     *
     * @param filePath 压缩照片的路径
     * @return 返回压缩处理后的照片
     */
    public static Bitmap getBitmap(String filePath) {

        Bitmap bitmap = null;

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max(
                (double) options.outWidth / 1024f,
                (double) options.outHeight / 1024f)));
        options.inJustDecodeBounds = false;
        bitmap = BitmapFactory.decodeFile(filePath, options);

        return bitmap;
    }

    private void uploadMemberImage(String compressedPath) {
        RequestBody requestFile1 = null;
        MultipartBody.Part part1 = null;
        File file1 = new File(compressedPath);
        requestFile1 = RequestBody.create(MediaType.parse("multipart/form-data"), file1);
        part1 = MultipartBody.Part.createFormData("cover", file1.getName(), requestFile1);

        RequestBody token = RequestBody.create(MediaType.parse("multipart/form-data"), mSharedPreferencesHelper.getString(BaseConstants.TOKEN));

        mPresenter.uploadMemberImage(token, part1);
    }

    @Override
    public void uploadMemberImageSuccess(UploadMemberImage uploadMemberImage) {

        ArmsUtils.snackbarText("頭像修改成功");
    }

    @Override
    public void updateUserInfoSuccess(UpdateUserInfo updateUserInfo) {

        ArmsUtils.snackbarText("修改成功");
        mSharedPreferencesHelper.putString(BaseConstants.NICKNAME, tvNiChengValue.getText().toString());
        mSharedPreferencesHelper.putString(BaseConstants.ADDRESS, tvDiZhiValue.getText().toString());
    }


    private void showEditTextDialog(String title, String hint, TextView view, int type) {
        final QMUIDialog.EditTextDialogBuilder builder = new QMUIDialog.EditTextDialogBuilder(SheZhiActivity.this);
        builder.setTitle(title)
                .setPlaceholder(hint)
                .setInputType(InputType.TYPE_CLASS_TEXT)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("確定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        CharSequence text = builder.getEditText().getText();
                        if (text != null && text.length() > 0) {
                            view.setText(text);
                            switch (type) {

                                case 1://暱称
//                                    mPresenter.updateUserInfo(mSharedPreferencesHelper.getString(BaseConstants.TOKEN), text.toString(), "", "", "");
                                    break;
                                case 2://地址
//                                    mPresenter.updateUserInfo(mSharedPreferencesHelper.getString(BaseConstants.TOKEN), "", text.toString(), "", "");
                                    break;
                                case 3://密码
//                                    mPresenter.updateUserInfo(mSharedPreferencesHelper.getString(BaseConstants.TOKEN), "", "", text.toString(), "");
                                    break;
                                case 4://邮箱
                                    mSharedPreferencesHelper.putString(BaseConstants.EMAIL, text.toString());
//                                    mPresenter.updateUserInfo(mSharedPreferencesHelper.getString(BaseConstants.TOKEN), "", "", "", text.toString());
                                    break;
                                case 5://电话
                                    mSharedPreferencesHelper.putString(BaseConstants.PHONE, text.toString());
                                    break;
                            }
                            dialog.dismiss();
                        } else {
                            Toast.makeText(SheZhiActivity.this, hint, Toast.LENGTH_SHORT).show();
                        }
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

    private void showConfirmMessageDialog() {
        new QMUIDialog.CheckBoxMessageDialogBuilder(SheZhiActivity.this)
                .setTitle("退出後是否刪除帳號信息?")
                .setMessage("刪除帳號信息")
                .setChecked(true)
                .addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                })
                .addAction("退出", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        mSharedPreferencesHelper.putString(BaseConstants.USERNAME, "");
                        mSharedPreferencesHelper.putString(BaseConstants.TOKEN, "");
                        mSharedPreferencesHelper.putString(BaseConstants.PASSWORD, "");

                        dialog.dismiss();
                        Utils.navigation(SheZhiActivity.this, RouterHub.XIAO_XING_LOGIN_LOGIN_ACTIVITY);
                        killMyself();
                    }
                })
                .create(mCurrentDialogStyle).show();
    }

}
